import axios from "axios";
import router from "@/router/index";
import store from "@/store";

import { Message } from "element-ui";

const port = location.port;
const $axios = axios.create({
  baseURL: `http://localhost:${port}`,
  withCredentials: true,
  timeout: 5000
});

$axios.interceptors.request.use(
  config => {
    const x_access_token = sessionStorage.getItem("Token");
    if (x_access_token) {
      // 有token时
      config.headers["Token"] = x_access_token; // 给请求头加token
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

$axios.interceptors.response.use(
  response => {
    const { code } = response.data || {};
    switch (+code) {
      case 404:
        Message({
          type: "error",
          message: response.data.msg
        });
        break;
      case 403:
        Message({
          type: "error",
          message: response.data.msg
        });
        break;
      case 500:
        Message({
          type: "waring",
          message: response.data.msg
        });
        store.dispatch("load/setLoading", false);
        break;
      case 501:
        Message({
          type: "waring",
          message: response.data.msg
        });
        store.dispatch("load/setLoading", false);
        break;
      case 401:
        Message({
          type: "waring",
          message: response.data.msg
        });
        sessionStorage.removeItem("Token");
        return router.push("/login");
        break;
      case 200:
        return response.data;
        break;
      default:
    }
  },
  error => {
    const { status } = error.response || {};
    switch (+status) {
      case 401:
        sessionStorage.removeItem("Token");
        return router.push("/login");
      default:
        Promise.reject(error);
    }
  }
);

export default $axios;
